package imService

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
	"vrcm/src/vrcm/app/admin/models"
	model "vrcm/src/vrcm/app/admin/models/live"
	"vrcm/src/vrcm/app/admin/service/dto/im"
	"vrcm/src/vrcm/envconfig"
	ext "vrcm/src/vrcm/envconfig"
)

type IMService struct {
	service.Service
}

var httpClient = &http.Client{}

// CreateIM 创建聊天室
func (e *IMService) CreateIM(d dto.IMCreateReqDto) (*dto.IMCreateResDto, error) {

	res := &dto.IMCreateResDto{}
	urlString := config.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/im/createIMGroup"
	params := url.Values{}
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	// 参数
	data := make(map[string]interface{})
	data["name"] = strconv.Itoa(int(time.Now().UnixMilli()))
	data["tenant_id"] = d.TenantId
	data["group_id"] = d.GroupId
	data["room_type"] = d.RoomType
	data["notification"] = d.Notification
	data["apply_join_option"] = d.ApplyJoinOption

	e.Log.Trace("创建聊天室请求路径：", urlPath)
	// Marshal
	bytesData, _ := json.Marshal(data)
	//response, err := http.Post("http://localhost:8084"+"/api/v1/im/createIMGroup", "application/json; charset=utf-8", bytes.NewReader(bytesData))
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))

	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if err != nil {
		return nil, err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Set("Content-Type", "application/json; charset=utf-8")
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	response, err := httpClient.Do(request)
	if err != nil {
		e.Log.Errorf("createIMGroup error:%s", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" {
		return res, errors.New(result.Get("message").String())
	}
	groupId := result.Get("data").Get("GroupId").String()
	res.GroupId = groupId
	return res, nil
}

// DestroyIM  摧毁聊天室
func (e *IMService) DestroyIM(d dto.IMDestroyReqDto) error {

	urlString := config.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/im/destroyIMGroup"
	params := url.Values{}
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["group_id"] = d.GroupId

	// Marshal
	bytesData, _ := json.Marshal(data)
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if err != nil {
		return err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Set("Content-Type", "application/json; charset=utf-8")
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	response, err := httpClient.Do(request)
	if err != nil {
		e.Log.Errorf("DestroyIM error:%s", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" && result.Get("code").String() != "301041" {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// MultiNoSpeak 批量禁言取消禁言
func (e *IMService) MultiNoSpeak(d dto.MultiNoSpeakReqDto) error {

	urlString := config.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/im/multiNoSpeak"
	params := url.Values{}
	Url, err := url.Parse(urlString)
	if err != nil {
		return err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["group_id"] = d.GroupId
	data["members_account"] = d.MembersAccount
	data["mute_time"] = d.MuteTime

	// Marshal
	bytesData, _ := json.Marshal(data)
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if err != nil {
		return err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Set("Content-Type", "application/json; charset=utf-8")
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	response, err := httpClient.Do(request)
	if err != nil {
		e.Log.Errorf("NoSpeak error:%s", err)
		return err
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return err
	}
	result := gjson.Parse(string(body))
	e.Log.Trace("MultiNoSpeak:", string(body))
	if result.Get("code").String() != "200" {
		return errors.New(result.Get("message").String())
	}
	return nil
}

// GetUserSign 获取签名
func (e *IMService) GetUserSign(d dto.GetUserSignReqDto) (*dto.GetUserSignResDto, error) {

	res := &dto.GetUserSignResDto{}

	urlString := config.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/im/getUserSign"
	params := url.Values{}
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	//params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()

	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["user_id"] = d.UserId

	e.Log.Trace(urlPath)
	// Marshal
	bytesData, _ := json.Marshal(data)
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if err != nil {
		return nil, err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Set("Content-Type", "application/json")
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	e.Log.Trace("GetUserSign:", request.Header.Get("Authorization"))
	response, err := httpClient.Do(request)
	if err != nil {
		e.Log.Errorf("createIMGroup error:%s", err)
		return res, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return res, err
	}
	e.Log.Trace("GetUserSign:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").String() != "200" {
		return res, errors.New(result.Get("message").String())
	}
	res.UserSign = result.Get("data").Get("user_sign").String()
	res.AppId = result.Get("data").Get("app_id").Int()
	res.UserId = result.Get("data").Get("user_id").String()
	res.TenantId = result.Get("data").Get("tenant_id").String()
	return res, nil
}

// GetGroupInfo 获取聊天室信息
func (e *IMService) GetGroupInfo(d dto.GetGroupInfoReqDto) (*[]model.GroupInfo, error) {

	res := make([]model.GroupInfo, 0, 10)

	urlString := config.ExtConfig.ServiceConfig.VrmServiceUrl + "/api/v1/im/getGroupInfo"
	params := url.Values{}
	Url, err := url.Parse(urlString)
	if err != nil {
		return nil, err
	}
	params.Set("permissionToken", "vsnb")
	Url.RawQuery = params.Encode()
	urlPath := Url.String()
	// 参数
	data := make(map[string]interface{})
	data["tenant_id"] = d.TenantId
	data["group_ids"] = d.GroupIds

	// Marshal
	bytesData, _ := json.Marshal(data)
	//response, err := http.Post("http://localhost:8084"+"/api/v1/im/getGroupInfo", "application/json; charset=utf-8", bytes.NewReader(bytesData))
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	request, err := http.NewRequest("POST", urlPath, bytes.NewReader(bytesData))
	if err != nil {
		return nil, err
	}
	if len(ext.ExtConfig.ServiceConfig.VsApiServiceUrl) > 0 {
		request.Header.Set("Authorization", "Bearer "+models.SuperToken)
		request.Header.Set("X-PS-Flag", "")
	} else {
		request.Header.Set("Authorization", "vsnb")
	}
	request.Header.Set("Content-Type", "application/json; charset=utf-8")
	//response, err := http.Post(urlPath, "application/json; charset=utf-8", bytes.NewReader(bytesData))
	response, err := httpClient.Do(request)
	if err != nil {
		e.Log.Errorf("GetGroupInfo error:%s", err)
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Errorf("读取响应体失败 error:%s", err)
		return nil, err
	}
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return nil, errors.New(result.Get("message").String())
	}

	err = json.Unmarshal([]byte(result.Get("data").String()), &res)
	if err != nil {
		return nil, err
	}

	return &res, nil
}
